#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

//餐厅买饭-----------条件变量实现合理化，互斥锁实现安全
//一对一的情况下
//
//
int count=0;  //表示柜台是否有饭 
pthread_mutex_t mutex;
pthread_cond_t cond;

void* customer(void* arg)
{
  while(1){
    //首先进行加锁
    pthread_mutex_lock(&mutex);
    if(count==0){
      //没有饭，阻塞
      pthread_cond_wait(&cond,&mutex);
    }
    //count==1 有饭，进行吃饭
    printf("%p 准备吃饭------再来一碗！\n",pthread_self());
    count=0;  
    pthread_cond_signal(&cond); //唤醒厨师来做饭
    pthread_mutex_unlock(&mutex);
  }
  return NULL;
}

void* cook(void* arg)
{
  while(1){
    pthread_mutex_lock(&mutex);
    if(count==1){
      //有饭，则阻塞
      pthread_cond_wait(&cond,&mutex);
    }
    //count==0 没有饭
    printf("%p 厨师做饭了-----快来吃饭！\n",pthread_self());
    count=1;
    pthread_cond_signal(&cond);  //唤醒顾客来吃饭
    pthread_mutex_unlock(&mutex);
  }
  return NULL;
}
int main()
{
  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&cond,NULL);
  pthread_t cus_tid,cook_tid ;  //创建两个线程
  int ret=pthread_create(&cus_tid,NULL,customer,NULL);
  if(ret!=0){
    perror("pthread_create error!\n");
    return -1;
  }

  ret=pthread_create(&cook_tid,NULL,cook,NULL);
  if(ret!=0){
    perror("pthread_create error!\n");
    return -1;
  }

  //线程等待
  pthread_join(cus_tid,NULL);
  pthread_join(cook_tid,NULL);

  //销毁
  pthread_mutex_destroy(&mutex);
  pthread_cond_destroy(&cond);

  return 0;
}
